package com.ruoyi.ums.auth.controller;

import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.UmsAccountAuth;
import com.ruoyi.system.api.domain.UmsAccountInfo;
import com.ruoyi.system.api.model.ThirdAuthUser;
import com.ruoyi.ums.ums.service.IUmsAccountInfoService;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.ums.auth.service.IUmsAccountAuthService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 授权信息Controller
 * 
 * @author ruoyi
 * @date 2021-03-03
 */
@RestController
@RequestMapping("/auth")
public class UmsAccountAuthController extends BaseController
{
    @Autowired
    private IUmsAccountAuthService umsAccountAuthService;
    @Autowired
    private IUmsAccountInfoService umsAccountInfoService;
    /**
     * 查询授权信息列表
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:list")
    @GetMapping("/list")
    public TableDataInfo list(UmsAccountAuth umsAccountAuth)
    {
        startPage();
        List<UmsAccountAuth> list = umsAccountAuthService.selectUmsAccountAuthList(umsAccountAuth);
        return getDataTable(list);
    }

    /**
     * 导出授权信息列表
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:export")
    @Log(title = "授权信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UmsAccountAuth umsAccountAuth) throws IOException
    {
        List<UmsAccountAuth> list = umsAccountAuthService.selectUmsAccountAuthList(umsAccountAuth);
        ExcelUtil<UmsAccountAuth> util = new ExcelUtil<UmsAccountAuth>(UmsAccountAuth.class);
        util.exportExcel(response, list, "auth");
    }

    /**
     * 获取授权信息详细信息
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(umsAccountAuthService.selectUmsAccountAuthById(id));
    }

    /**
     * 获取当前用户信息
     */
    @PostMapping("/info")
    public R<ThirdAuthUser> info(@RequestBody AuthUser authUser)
    {
        UmsAccountAuth query = new UmsAccountAuth();
        ThirdAuthUser thirdAuthUser = new ThirdAuthUser();
        query.setIdentifier(authUser.getUuid());
        query.setIdentityType(authUser.getSource());
        UmsAccountAuth umsAccountAuth = umsAccountAuthService.selectUmsAccountInfoByIdentifier(query);
        long currentMillis = System.currentTimeMillis()/1000;
        if (StringUtils.isNull(umsAccountAuth))
        {
            //自动注册绑定并登录用户
            //先新增umsaccountInfo信息
            UmsAccountInfo entity = new UmsAccountInfo();
            String uuid = RandomUtil.randomString(16);
            entity.setAccountId(uuid);
            entity.setNickname(authUser.getNickname());
            entity.setAvatar(authUser.getAvatar());
            entity.setUsername(authUser.getUsername());
            entity.setAccountStatus("0");
            entity.setAccountPassword(SecurityUtils.encryptPassword(uuid));
            entity.setSex(StringUtils.isNull(authUser.getGender())?"-1":authUser.getGender().getCode());
            entity.setEmail(authUser.getEmail());
            entity.setCreateTime(DateTime.now());
            if(umsAccountInfoService.insertUmsAccountInfo(entity)>0){
                UmsAccountAuth umsAccountAuth1 = new UmsAccountAuth();
                umsAccountAuth1.setAccountId(uuid);
                umsAccountAuth1.setIdentityType(authUser.getSource());
                umsAccountAuth1.setIdentifier(authUser.getUuid());
                umsAccountAuth1.setCredential(authUser.getToken().getAccessToken());
                umsAccountAuth1.setExpireIn(currentMillis+authUser.getToken().getExpireIn());//超时秒数
                umsAccountAuth1.setRefreshToken(authUser.getToken().getRefreshToken());
                umsAccountAuth1.setRefreshTokenExpireIn(currentMillis+authUser.getToken().getRefreshTokenExpireIn());
                umsAccountAuth1.setStatus("0");
                umsAccountAuth1.setBindTime(DateTime.now());
                umsAccountAuth1.setAuthData(JSONUtil.toJsonStr(authUser));
                umsAccountAuthService.insertUmsAccountAuth(umsAccountAuth1);
                umsAccountAuth = umsAccountAuthService.selectUmsAccountInfoByIdentifier(umsAccountAuth1);
                thirdAuthUser.setUmsAccountAuth(umsAccountAuth);
                thirdAuthUser.setUmsAccountInfo(entity);
            }
        }
        else{
            //更新access_token，
                umsAccountAuth.setCredential(authUser.getToken().getAccessToken());
                umsAccountAuth.setExpireIn(currentMillis+authUser.getToken().getExpireIn());
                umsAccountAuth.setRefreshToken(authUser.getToken().getRefreshToken());
                umsAccountAuth.setRefreshTokenExpireIn(currentMillis+authUser.getToken().getRefreshTokenExpireIn());
                umsAccountAuthService.updateUmsAccountAuth(umsAccountAuth);
            UmsAccountInfo currentUser = umsAccountInfoService.selectUmsAccountInfoById(umsAccountAuth.getAccountId());
            thirdAuthUser.setUmsAccountInfo(currentUser);
            thirdAuthUser.setUmsAccountAuth(umsAccountAuth);
        }
        return R.ok(thirdAuthUser);
    }

    /**
     * 新增授权信息
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:add")
    @Log(title = "授权信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UmsAccountAuth umsAccountAuth)
    {
        return toAjax(umsAccountAuthService.insertUmsAccountAuth(umsAccountAuth));
    }

    /**
     * 修改授权信息
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:edit")
    @Log(title = "授权信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UmsAccountAuth umsAccountAuth)
    {
        return toAjax(umsAccountAuthService.updateUmsAccountAuth(umsAccountAuth));
    }

    /**
     * 删除授权信息
     */
    @PreAuthorize(hasPermi = "umsAuth:auth:remove")
    @Log(title = "授权信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(umsAccountAuthService.deleteUmsAccountAuthByIds(ids));
    }
}
